const getAuthToken = () => {
  return new Promise(async (resolve, reject) => {
    let res
    if ($dd.env.platform !== 'notInDingTalk') {
      // 你要执行的钉钉api
      const corpId = window.location.search?.split('?corpId=')[1]
      if (!corpId) reject()
      const codeRes = await getAuthCode(corpId)
      const code = codeRes?.code
      if (!code) reject()
      const userInfoRes = await $get(`/api/v1/app/token/dingding/user/${code}`)
      const {userid} = userInfoRes?.data
      if (!userid) reject()
      const loginRes = await $get(`/bus/api/v1/token/ding/login/${userid}`)
      res = loginRes?.data
    } else if (['development', 'test'].includes(import.meta.env.MODE)) {
      const loginRes = await $post('/bus/api/v1/token', {
        name: 'admin',
        password: '9B8E8AB2CC7E4B5C81FAE47B9D2671E9',
      })
      res = loginRes?.data
    }
    const {accessToken} = res
    accessToken ? resolve(accessToken) : reject()
  })
}

const getAuthCode = corpId => {
  return new Promise((resolve, reject) => {
    $dd.ready(() => {
      $dd.runtime.permission.requestAuthCode({
        corpId: corpId, // 企业id
        onSuccess: resolve,
        onFail: reject,
      })
    })
  })
}

export default getAuthToken
